package org.wutopia.leocloud.library.common.infrastructure.config;

import com.nimbusds.jwt.JWTClaimsSet;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.wutopia.leocloud.library.common.domain.account.Account;
import org.wutopia.leocloud.library.common.domain.security.CurrentAccount;
import org.wutopia.leocloud.library.common.infrastructure.utility.JwtUtility;


import java.nio.file.AccessDeniedException;
import java.util.List;

@Component
public class JwtUserArgumentResolver implements HandlerMethodArgumentResolver {

    private static final Logger log = LoggerFactory.getLogger(JwtUserArgumentResolver.class);

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurrentAccount.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
        // 从请求头获取JWT
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        log.warn(request.getHeader("Authorization"));
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            // 解析JWT获取用户信息（示例：用户名）
            JWTClaimsSet claims = JwtUtility.verifyAndParseToken(token);
            String accountId = claims.getSubject();                 // 用户 ID
            String username = (String) claims.getClaim("username"); // 用户名称
            List<String> authorities = (List<String>) claims.getClaim("authorities"); // 权限列表
            Account account = new Account();
            account.setUsername(username);
            account.setId(Integer.valueOf(accountId));
            return account; // 替换为实际用户对象
        }
        throw new AccessDeniedException("无效的JWT令牌");
    }
}
